package com.dropdb.demo.service.impl;

import com.dropdb.demo.bean.Keyword;
import com.dropdb.demo.bean.KeywordExample;
import com.dropdb.demo.bean.SearchHistoryExample;
import com.dropdb.demo.bean.vo.SearchHistoryVO;
import com.dropdb.demo.mapper.KeywordMapper;
import com.dropdb.demo.mapper.SearchHistoryMapper;
import com.dropdb.demo.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    KeywordMapper keywordMapper;
    @Autowired
    SearchHistoryMapper searchHistoryMapper;

    /**
     * 搜索界面首页
     * @return
     */
    @Override
    public HashMap<String, Object> getIndexOfSearch(Integer userId) {
        // 获取默认关键字
        KeywordExample defaultKeyExample = new KeywordExample();
        // 根据sort_order降序查询
        defaultKeyExample.setOrderByClause("sort_order desc");
        defaultKeyExample.createCriteria().andIsDefaultEqualTo(true).andDeletedEqualTo(false);
        List<Keyword> defaultKeys = keywordMapper.selectByExample(defaultKeyExample);
        Keyword defaultKey = defaultKeys.get(0);
        // 获取热门关键字
        KeywordExample hotKeyExample = new KeywordExample();
        hotKeyExample.setOrderByClause("sort_order desc limit 20");
        hotKeyExample.createCriteria().andIsHotEqualTo(true).andDeletedEqualTo(false);
        List<Keyword> hotKeys = keywordMapper.selectByExample(hotKeyExample);
        // 获取个人搜索历史
        List<SearchHistoryVO> histories = new ArrayList<>();
        if (userId != null) {
            histories = searchHistoryMapper.getSearchHistoryOnlyKey(userId);
        }
        // 添加进map
        HashMap<String, Object> map = new HashMap<>();
        map.put("defaultKeyword", defaultKey);
        map.put("hotKeywordList", hotKeys);
        map.put("historyKeywordList", histories);
        return map;
    }


    /**
     * 根据关键字在关键字表中查询类似关键字，以帮助用户快速查询
     * @param keyword
     * @return
     */
    @Override
    public List<String> searchHelper(String keyword) {
        List<String> likeKeywords = keywordMapper.selectOnlyLikeKeyword(keyword);
        return likeKeywords;
    }


    /**
     * 根据用户id清除查询历史
     * @param userId
     */
    @Override
    public void clearHistory(Integer userId) {
        SearchHistoryExample example = new SearchHistoryExample();
        example.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        searchHistoryMapper.deleteByExample(example);
    }
}
